<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :template-url="templateUrl" />
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { excelToDate } from '@/utils'
import { uploadEmployee } from '@/api/employees'
export default {
  name: 'UploadExcel',
  components: { UploadExcelComponent },
  data() {
    return {
    }
  },
  computed: {
    type() {
      return this.$route.query.type
    },
    templateUrl() {
      if (this.type === 'employee') {
        return '/excel/员工导入模板.xlsx'
      } else {
        return '/excel/123.xlsx'
      }
    }
  },
  methods: {
    async handleSuccess({ results, header }) {
    //   console.log(results, header)
      if (this.type === 'employee') {
        const data = this.resolveExcelData(results)
        //   console.log(data)
        await uploadEmployee(data)
      }
      this.$message.success('导入成功')
      this.$router.back()
    },
    resolveExcelData(data) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '聘用形式': 'formOfEmployment',
        '部门': 'departmentName'
      }
      return data.map(item => {
        const obj = {}
        for (const key in item) {
        //   console.log(key)
          if (key === '入职日期' || key === '转正日期') {
            obj[userRelations[key]] = excelToDate(item[key])
          } else {
            obj[userRelations[key]] = item[key]
          }
        //   console.log(userRelations[key])
        //   console.log(item[key])
        }
        return obj
      })
    }
  }
}
</script>
